package org.eclipseuseradmin.internal.demo;

import org.eclipse.core.runtime.IAdapterFactory;
import org.eclipseuseradmin.ui.GroupAdapter;
import org.eclipseuseradmin.ui.IGroup;
import org.eclipseuseradmin.ui.IRole;
import org.eclipseuseradmin.ui.IRoleElement;
import org.eclipseuseradmin.ui.IUser;
import org.eclipseuseradmin.ui.RoleAdapter;
import org.eclipseuseradmin.ui.UserAdapter;
import org.osgi.service.useradmin.Group;
import org.osgi.service.useradmin.Role;
import org.osgi.service.useradmin.User;

public class RoleAdapterFactory implements IAdapterFactory {

	public Object getAdapter(Object adaptable, Class adapter) {

		if (!(adaptable instanceof Role)) {
			return null;
		}

		Role role = (Role) adaptable;

		if (adaptable instanceof User && isObjectClass(role, "user")
				&& (adapter == IUser.class || adapter == IRoleElement.class)) {

			UserAdapter adapterInstance = new UserAdapter((User) adaptable);
			return adapterInstance;
		}
		if (adaptable instanceof Group && isObjectClass(role, "group")
				&& (adapter == IGroup.class || adapter == IRoleElement.class)) {

			GroupAdapter adapterInstance = new GroupAdapter((Group) adaptable);
			adapterInstance
					.setAcceptedChildren(new String[] { "user", "group" });
			return adapterInstance;
		}
		if (adaptable instanceof Group && isObjectClass(role, "role")
				&& (adapter == IRole.class || adapter == IRoleElement.class)) {

			RoleAdapter adapterInstance = new RoleAdapter((Group) adaptable);
			adapterInstance.setAcceptedChildren(new String[] { "user", "group",
					"role", "customer" });
			return adapterInstance;
		}
		if (adaptable instanceof User
				&& isObjectClass(role, "customer")
				&& (adapter == ICustomer.class || adapter == IRoleElement.class)) {

			CustomerAdapter adapterInstance = new CustomerAdapter(
					(User) adaptable);
			return adapterInstance;
		}

		return null;
	}

	private boolean isObjectClass(Role role, String objectClass) {

		String currentObjectClass = (String) role.getProperties().get(
				"objectclass");
		if (currentObjectClass == null) {
			return true;
		}
		return currentObjectClass.equalsIgnoreCase(objectClass);
	}

	public Class[] getAdapterList() {
		return new Class[] { IUser.class, IGroup.class, IRole.class,
				IRoleElement.class, ICustomer.class };
	}

}
